/* ========================================================================
 * Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
 *
 * OPC Foundation MIT License 1.00
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 * The complete license agreement can be found here:
 * http://opcfoundation.org/License/MIT/1.00/
 * ======================================================================*/

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace Opc.Ua.Bindings
{
    /// <summary>
    /// Stores the results of an asynchronous operation.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ChannelAsyncOperation<T> : IAsyncResult, IDisposable
    {
        /// <summary>
        /// Initializes the object with a callback
        /// </summary>
        public ChannelAsyncOperation(int timeout, AsyncCallback callback, object asyncState, ILogger logger)
        {
            m_callback = callback;
            m_asyncState = asyncState;
            m_synchronous = false;
            m_completed = false;
            m_logger = logger;

            if (timeout is > 0 and not int.MaxValue)
            {
                m_timer = new Timer(new TimerCallback(OnTimeout), null, timeout, Timeout.Infinite);
            }
        }

        /// <summary>
        /// Frees any unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// An overrideable version of the Dispose.
        /// </summary>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                lock (m_lock)
                {
                    Utils.SilentDispose(m_timer);
                    m_timer = null;

                    if (m_event != null)
                    {
                        m_event.Set();
                        m_event.Dispose();
                        m_event = null;
                    }

                    if (m_tcs != null)
                    {
                        if (!m_tcs.Task.IsCompleted)
                        {
                            m_tcs.TrySetCanceled();
                        }
                        m_tcs = null;
                    }
                }
            }
        }

        /// <summary>
        /// Called when an asynchronous operation completes.
        /// </summary>
        public bool Complete(T response)
        {
            return InternalComplete(true, response);
        }

        /// <summary>
        /// Called when an asynchronous operation completes.
        /// </summary>
        public bool Complete(bool doNotBlock, T response)
        {
            return InternalComplete(doNotBlock, response);
        }

        /// <summary>
        /// Called when an asynchronous operation completes.
        /// </summary>
        public bool Fault(ServiceResult error)
        {
            return InternalComplete(true, error);
        }

        /// <summary>
        /// Called when an asynchronous operation completes.
        /// </summary>
        public bool Fault(bool doNotBlock, ServiceResult error)
        {
            return InternalComplete(doNotBlock, error);
        }

        /// <summary>
        /// Called when an asynchronous operation completes.
        /// </summary>
        public bool Fault(uint code, string format, params object[] args)
        {
            return InternalComplete(true, ServiceResult.Create(code, format, args));
        }

        /// <summary>
        /// Called when an asynchronous operation completes.
        /// </summary>
        public bool Fault(bool doNotBlock, uint code, string format, params object[] args)
        {
            return InternalComplete(doNotBlock, ServiceResult.Create(code, format, args));
        }

        /// <summary>
        /// Called when an asynchronous operation completes.
        /// </summary>
        public bool Fault(Exception e, uint defaultCode, string format, params object[] args)
        {
            return InternalComplete(true, ServiceResult.Create(e, defaultCode, format, args));
        }

        /// <summary>
        /// Called when an asynchronous operation completes.
        /// </summary>
        public bool Fault(
            bool doNotBlock,
            Exception e,
            uint defaultCode,
            string format,
            params object[] args)
        {
            return InternalComplete(doNotBlock, ServiceResult.Create(e, defaultCode, format, args));
        }

        /// <summary>
        /// The response returned from the server.
        /// </summary>
        /// <exception cref="ServiceResultException"></exception>
        public T End(int timeout, bool throwOnError = true)
        {
            // check if the request has already completed.
            bool mustWait = false;

            lock (m_lock)
            {
                mustWait = !m_completed;

                if (mustWait)
                {
                    m_event = new ManualResetEvent(false);
                }
            }

            // wait for completion.
            if (mustWait)
            {
                try
                {
                    if (!m_event.WaitOne(timeout) && throwOnError)
                    {
                        throw new ServiceResultException(StatusCodes.BadRequestInterrupted);
                    }
                }
                finally
                {
                    lock (m_lock)
                    {
                        // Dispose the event
                        if (m_event != null)
                        {
                            m_event.Dispose();
                            m_event = null;
                        }
                    }
                }
            }

            // return the response.
            lock (m_lock)
            {
                if (m_error != null && throwOnError)
                {
                    throw new ServiceResultException(m_error);
                }

                return m_response;
            }
        }

        /// <summary>
        /// The awaitable response returned from the server.
        /// </summary>
        /// <exception cref="ServiceResultException"></exception>
        public async Task<T> EndAsync(
            int timeout,
            bool throwOnError = true,
            CancellationToken ct = default)
        {
            // check if the request has already completed.
            bool mustWait = false;

            lock (m_lock)
            {
                mustWait = !m_completed;

                if (mustWait)
                {
                    m_tcs = new TaskCompletionSource<bool>(
                        TaskCreationOptions.RunContinuationsAsynchronously);
                }
            }

            // wait for completion.
            if (mustWait)
            {
                bool badRequestInterrupted = false;
                try
                {
                    Task<bool> awaitableTask = m_tcs.Task;
#if NET6_0_OR_GREATER
                    if (timeout != int.MaxValue)
                    {
                        awaitableTask = m_tcs.Task
                            .WaitAsync(TimeSpan.FromMilliseconds(timeout), ct);
                    }
                    else if (ct != default)
                    {
                        awaitableTask = m_tcs.Task.WaitAsync(ct);
                    }
#else
                    if (timeout != int.MaxValue || ct != default)
                    {
                        Task completedTask = await Task.WhenAny(m_tcs.Task, Task.Delay(timeout, ct))
                            .ConfigureAwait(false);
                        if (m_tcs.Task == completedTask)
                        {
                            if (!m_tcs.Task.Result)
                            {
                                badRequestInterrupted = true;
                            }
                        }
                        else
                        {
                            m_tcs.TrySetCanceled(ct);
                            badRequestInterrupted = true;
                        }
                    }
                    else
#endif
                    if (!await awaitableTask.ConfigureAwait(false))
                    {
                        badRequestInterrupted = true;
                    }
                }
                catch (TimeoutException)
                {
                    badRequestInterrupted = true;
                }
                catch (TaskCanceledException)
                {
                    badRequestInterrupted = true;
                }
                finally
                {
                    lock (m_lock)
                    {
                        m_tcs = null;
                    }
                }

                if (badRequestInterrupted && throwOnError)
                {
                    throw new ServiceResultException(StatusCodes.BadRequestInterrupted);
                }
            }

            // return the response.
            lock (m_lock)
            {
                if (m_error != null && throwOnError)
                {
                    throw new ServiceResultException(m_error);
                }

                return m_response;
            }
        }

        /// <summary>
        /// Stores additional state information associated with the operation.
        /// </summary>
        public IDictionary<string, object> Properties
        {
            get
            {
                lock (m_lock)
                {
                    m_properties ??= [];

                    return m_properties;
                }
            }
        }

        /// <summary>
        /// Return the result of the operation.
        /// </summary>
        public ServiceResult Error => m_error ?? ServiceResult.Good;

        /// <inheritdoc/>
        public object AsyncState
        {
            get
            {
                lock (m_lock)
                {
                    return m_asyncState;
                }
            }
        }

        /// <inheritdoc/>
        public WaitHandle AsyncWaitHandle
        {
            get
            {
                lock (m_lock)
                {
                    m_event ??= new ManualResetEvent(m_completed);

                    return m_event;
                }
            }
        }

        /// <inheritdoc/>
        public bool CompletedSynchronously
        {
            get
            {
                lock (m_lock)
                {
                    return m_synchronous;
                }
            }
        }

        /// <inheritdoc/>
        public bool IsCompleted
        {
            get
            {
                lock (m_lock)
                {
                    return m_completed;
                }
            }
        }

        /// <summary>
        /// Called when the operation times out.
        /// </summary>
        private void OnTimeout(object state)
        {
            if (m_timer != null)
            {
                InternalComplete(false, new ServiceResult(StatusCodes.BadRequestTimeout));
            }
        }

        /// <summary>
        /// Called when an asynchronous operation completes.
        /// </summary>
        protected virtual bool InternalComplete(bool doNotBlock, object result)
        {
            lock (m_lock)
            {
                // ignore multiple calls (i.e. a timeout after a response or vise versa).
                if (m_completed)
                {
                    return false;
                }

                if (result is T typed)
                {
                    m_response = typed;
                }
                else
                {
                    m_error = result as ServiceResult;
                }

                m_completed = true;

                if (m_timer != null)
                {
                    m_timer.Dispose();
                    m_timer = null;
                }

                m_event?.Set();

                m_tcs?.TrySetResult(true);
            }

            AsyncCallback callback = m_callback;
            if (callback != null)
            {
                if (doNotBlock)
                {
                    Task.Run(() => callback(this));
                }
                else
                {
                    try
                    {
                        callback(this);
                    }
                    catch (Exception e)
                    {
                        m_logger.LogError(
                            e,
                            "ClientChannel: Unexpected error invoking AsyncCallback.");
                    }
                }
            }

            return true;
        }

        private readonly Lock m_lock = new();
        private readonly AsyncCallback m_callback;
        private readonly object m_asyncState;
        private readonly bool m_synchronous;
        private readonly ILogger m_logger;
        private bool m_completed;
        private ManualResetEvent m_event;
        private TaskCompletionSource<bool> m_tcs;
        private T m_response;
        private ServiceResult m_error;
        private Timer m_timer;
        private Dictionary<string, object> m_properties;
    }
}
